package com.yiwu.common.component;

import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @version 1.0
 * @description TODO
 * @date 2024/5/29 0:15
 */
@Component
public class RedisComponent {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public Long getHeartBeat(String userId) {
        String res = stringRedisTemplate.opsForValue().get("heatBeat" + userId);
        return res == null ? null : Long.parseLong(res);
    }

    public void saveHeartBeat(String userId) {
        stringRedisTemplate.opsForValue().set("heatBeat" + userId, String.valueOf(System.currentTimeMillis()), 6, TimeUnit.SECONDS);
    }

    public void removeHeartBeat(String userId) {
        stringRedisTemplate.delete("heatBeat" + userId);
    }


    public String getUserId(String token) {
        return stringRedisTemplate.opsForValue().get(token + "yiwu");
    }

    public void saveMessage(String key, String chatMessageJson, Long timestamp) {
        stringRedisTemplate.opsForZSet().add(key, chatMessageJson, timestamp);
        // 获取当前有序集合中的消息数量
        Long size = stringRedisTemplate.opsForZSet().zCard(key);

        // 如果超过了 100 条，则删除最旧的一条消息
        if (size != null && size > 100) {
            stringRedisTemplate.opsForZSet().removeRange(key, 100, 100);
        }
    }

    public void saveSession(String sessionId, String userId) {
        stringRedisTemplate.opsForSet().add("sessionId&userId" + userId, sessionId);
    }

    public void removeSession(String userId) {
        stringRedisTemplate.delete("sessionId&userId" + userId);
    }

    public Boolean getSession(String sessionId, String userId) {
        Set<String> members = stringRedisTemplate.opsForSet().members("sessionId&userId" + userId);
        return members != null && members.contains(sessionId);
    }
}
